var asyncjs = require('async');
var Enhancer;
// 价格同步接口的配置查询SQL，同步所有配件信息，包括料号、图号、价格、单位等
var api_sql = "select object_value from sys_config where object_name = 'EP_SYNC_SPART' LIMIT 1";

const chunkSize = 100;
function chunkArray(array, chunkSize) {
    let result = [];
    for (let i = 0; i < array.length; i += chunkSize) {
        result.push(array.slice(i, i + chunkSize));
    }
    return result;
}

module.exports = {
    // 引入Enhancer
    init: function (enhancer) {
        Enhancer = enhancer;
    },
    update: function () {
        var db = Enhancer.getDatabaseService();

        db.execute(api_sql, [], function (err, result) {
            if (err) {
                console.log(err)
                console.log('配件信息集成接口同步出错，请联系管理员！');
                return
            }
            if (!result.rows.length) {
                console.log('未找到配件信息同步的集成接口配置，请联系管理员！');
                return false;
            } else {
                //获取配件信息同步集成接口地址

                console.log('配件信息集成接口：', result.rows[0].object_value);
                var sync_url = result.rows[0].object_value;

                var request = require('request');

                request(sync_url, function (error, response, body) {   //body为返回的数据

                    if (!error) {
                        //将body转为json进行处理
                        const jsonString = body.toString();
                        const jsonData = JSON.parse(jsonString);

                        const dataArray = jsonData.data;


                        if (dataArray && dataArray.length > 1) {



                            // 构建批量更新的 SQL 语句
                            let sql = 'INSERT INTO df_spart (uid, part_no, drawing_no, name, price, part_status, part_active_date, meins, werks, btype, mtype, stype) VALUES ';
                            let values = [];
                            let updates = [];

                            dataArray.forEach((item) => {
                                const uid = mysql.escapeId(uuid());
                                const partNo = mysql.escape(item.matnr);
                                const drawingNo = mysql.escape(item.zeinr);
                                const name = mysql.escape(item.maktx);
                                const price = mysql.escape(item.channelprice);
                                const meins = mysql.escape(item.meins);
                                const werks = mysql.escape(item.werks);
                                const btype = mysql.escape(item.btype);
                                const mtype = mysql.escape(item.mtype);
                                const stype = mysql.escape(item.stype);

                                sql += `(${uid}, ${partNo}, ${drawingNo}, ${name}, ${price}, '1', CURDATE(), ${meins}, ${werks}, ${btype}, ${mtype}, ${stype}), `;
                                values.push(uid, partNo, drawingNo, name, price, meins, werks, btype, mtype, stype);

                                updates.push(
                                    `${drawingNo} ON DUPLICATE KEY UPDATE drawing_no = ${drawingNo}, name = ${name}, price = ${price}, meins = ${meins}`
                                );
                            });

                            // 移除最后一个逗号
                            sql = sql.slice(0, -2) + ' ON DUPLICATE KEY UPDATE ' + updates.join(', ');


                            db.execute(sql2, values, function (err2, result2) {
                                console.log(j++);
                                if (err2) {
                                    /* 做一些错误处理，如果环境中有 done 方法，则直接 done(err) */
                                    console.log('insert error');
                                    console.log(err2);
                                    return

                                } else {
                                    //   console.log('配件信息成功，共', dataArray.length, '条数据被更新');
                                }

                            });
                        } else {
                            console.log('无数据更新');
                        }
                    }

                });

            }

        });

    }

};